package cn.gengar.domain.activity.service.trial.node;

import cn.gengar.domain.activity.model.entity.MarketProductEntity;
import cn.gengar.domain.activity.model.entity.TrialBalanceEntity;
import cn.gengar.domain.activity.model.valobj.GroupBuyActivityDiscountVO;
import cn.gengar.domain.activity.model.valobj.SkuVO;
import cn.gengar.domain.activity.service.discount.IDiscountCalculateService;
import cn.gengar.domain.activity.service.trial.AbstractGroupBuyMarketSupport;
import cn.gengar.domain.activity.service.trial.factory.DefaultActivityStrategyFactory;
import cn.gengar.domain.activity.service.trial.thread.QueryGroupBuyActivityDiscountVOThreadTask;
import cn.gengar.domain.activity.service.trial.thread.QuerySkuVOFromDBThreadTask;
import cn.gengar.types.design.framework.tree.StrategyHandler;
import cn.gengar.types.enums.ResponseCode;
import cn.gengar.types.exception.AppException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MarkeNode extends AbstractGroupBuyMarketSupport<MarketProductEntity,
        DefaultActivityStrategyFactory.DynamicContext,
        TrialBalanceEntity> {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private ErrorNode errorNode;
    @Resource
    private TagNode tagNode;
    @Resource
    private Map<String, IDiscountCalculateService> discountCalculateServiceMap;

    @Override
    public void mutiThread(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        // 异步查询活动配置
        QueryGroupBuyActivityDiscountVOThreadTask discountVOThreadTask = new QueryGroupBuyActivityDiscountVOThreadTask(requestParameter.getSource(), requestParameter.getChannel(), requestParameter.getGoodsId(), repository);
        FutureTask<GroupBuyActivityDiscountVO> discountVOFutureTask = new FutureTask<>(discountVOThreadTask);
        threadPoolExecutor.execute(discountVOFutureTask);

        QuerySkuVOFromDBThreadTask skuVOFromDBThreadTask = new QuerySkuVOFromDBThreadTask(requestParameter.getGoodsId(), repository);
        FutureTask<SkuVO> skuVOFutureTask = new FutureTask<>(skuVOFromDBThreadTask);
        threadPoolExecutor.execute(skuVOFutureTask);

        dynamicContext.setGroupBuyActivityDiscountVO(discountVOFutureTask.get(timeout, TimeUnit.MINUTES));
        dynamicContext.setSkuVO(skuVOFutureTask.get(timeout, TimeUnit.MINUTES));

        log.info("查询活动配置 marketNode userId:{},{}", requestParameter.getUserId(), JSON.toJSONString(dynamicContext));
    }

    @Override
    public TrialBalanceEntity doApply(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        log.info("拼团商品查询试算服务 MarketNode doApply userId:{},requestParameter:{}", requestParameter.getUserId(), JSON.toJSONString(requestParameter));

        GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = dynamicContext.getGroupBuyActivityDiscountVO();
        if (Objects.isNull(groupBuyActivityDiscountVO)) {
            return router(requestParameter, dynamicContext);
        }
        IDiscountCalculateService discountCalculateService = discountCalculateServiceMap.get(groupBuyActivityDiscountVO.getGroupBuyDiscount().getMarketPlan());

        if (Objects.isNull(discountCalculateService)) {
            throw new AppException(ResponseCode.E0001.getCode(), ResponseCode.E0001.getInfo());
        }

        SkuVO skuVO = dynamicContext.getSkuVO();
        if (Objects.isNull(skuVO)) {
            return router(requestParameter, dynamicContext);
        }
        BigDecimal payPrice = discountCalculateService.calculate(requestParameter.getUserId(),
                skuVO.getOriginalPrice(),
                groupBuyActivityDiscountVO.getGroupBuyDiscount());

        dynamicContext.setDeductionPrice(skuVO.getOriginalPrice().subtract(payPrice));
        dynamicContext.setPayPrice(payPrice);

        return router(requestParameter, dynamicContext);
    }

    @Override
    public StrategyHandler<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> get(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        // 不存在配置的拼团活动，走异常节点
        if (Objects.isNull(dynamicContext.getGroupBuyActivityDiscountVO()) ||
                Objects.isNull(dynamicContext.getSkuVO()) ||
                Objects.isNull(dynamicContext.getDeductionPrice())) {
            return errorNode;
        }
        return tagNode;
    }
}
